package com.zhong.gang.app.db;

import android.content.Context;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;


public class UserUtils {
    private static UserUtils userUtils;
    private static UserDao userDao;

    public UserUtils(Context context) {
        userDao = new UserDao(context);
    }

    public static UserUtils getIntent(Context context) {
        if (userUtils == null || userDao == null) {
            userUtils = new UserUtils(context);
        }
        return userUtils;
    }

    public UserDao getUserDao() {
        return userDao;
    }

    /**
     * 保存数据
     *
     * @param userBean
     */
    public void saveUser(UserBean userBean,boolean loginStatus) {
        userDao.deleteAll();
        userBean.setLogin(loginStatus);
        userDao.save(userBean);
    }

    /**
     * 保存数据
     *
     * @param userBean
     */
    public void saveUser(UserBean userBean) {
        saveUser(userBean,true);
    }


    /**
     * 获取User
     *
     * @return
     */
    public UserBean getUser() {
        UserBean userBean = userDao.queryForFirst();
        if (userBean == null)
            userBean = new UserBean();
        return userBean;
    }

    public int getMaterialYardId(){
        UserBean userBean = getUser();
        if (userBean.getMaterialYardId() == 0)
            return userBean.getSteelMillId();
        return userBean.getMaterialYardId();
    }

    /**
     * 获取角色ID
     * @return
     */
    public int getRoleId(){
        String roleList = getUser().getRoleStr();
        try {
            JSONArray jsonArray = new JSONArray(roleList);
            for (int n = 0 ; n < jsonArray.length();n++){
                JSONObject jsonObject = jsonArray.getJSONObject(n);
                return jsonObject.getInt("id");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return 0;
    }
}
